package ru.mcfr.oxygen.framework.operations.table;

import ro.sync.ecss.extensions.api.*;
import ro.sync.ecss.extensions.api.node.AttrValue;
import ro.sync.ecss.extensions.api.node.AuthorDocumentFragment;
import ro.sync.ecss.extensions.api.node.AuthorElement;
import ro.sync.ecss.extensions.api.node.AuthorNode;

import javax.swing.text.BadLocationException;
import java.util.List;

/**
 * Created by IntelliJ IDEA.
 * User: ws
 * Date: 4/14/11
 * Time: 1:27 PM
 * To change this template use File | Settings | File Templates.
 */
public class JoinCellInColumnOperation implements AuthorOperation {



    public void doOperation(AuthorAccess authorAccess, ArgumentsMap argumentsMap) throws IllegalArgumentException, AuthorOperationException {
        AuthorDocumentController controller = authorAccess.getDocumentController();
        controller.beginCompoundEdit();
        if (!authorAccess.getEditorAccess().hasSelection()){
            try {

                String mode = "join";
                try {
                    mode = argumentsMap.getArgumentValue("режим").toString();
                } catch (Exception e) {
                    e.printStackTrace();
                }

                int initialCaretOffset = authorAccess.getEditorAccess().getCaretOffset();

                AuthorNode selectedCell = controller.getNodeAtOffset(initialCaretOffset);
                while (!selectedCell.getName().equalsIgnoreCase("ячейка"))
                    selectedCell = selectedCell.getParent();

                AuthorNode table = selectedCell;
                while (!table.getName().equalsIgnoreCase("таблица"))
                    table = table.getParent();

                if (mode.equalsIgnoreCase("join")) {

                    int[] cellIndex = authorAccess.getTableAccess().getTableCellIndex((AuthorElement) selectedCell);

                    Integer thisRowSpan = 1;
                    try {
                        thisRowSpan = Integer.valueOf(((AuthorElement) selectedCell).getAttribute("rowspan").getValue());
                    } catch (Exception e) {
                    }

                    AuthorElement belowCell = authorAccess.getTableAccess().getTableCellBelow((AuthorElement) selectedCell);

                    int[] collSpanInfo = authorAccess.getTableAccess().getTableColSpanIndices(belowCell);

                    if (collSpanInfo[0] != collSpanInfo[1]){
                        authorAccess.getWorkspaceAccess().showInformationMessage("Для объединения разделите нижнюю ячейку.");
                        return;
                    }

                    Integer belRowSpan = 1;
                    try {
                        belRowSpan = Integer.valueOf(belowCell.getAttribute("rowspan").getValue());
                    } catch (Exception e) {
                    }

                    List<AuthorNode> contentOfBeCell = belowCell.getContentNodes();
                    int startFrag = 0;
                    int endFrag = 0;

                    try{
                        startFrag = contentOfBeCell.get(0).getStartOffset();
                        endFrag = contentOfBeCell.get(contentOfBeCell.size() - 1).getEndOffset();
                    } catch (Exception e) {}

                    if (endFrag > startFrag){

                        AuthorDocumentFragment fragOfBeCell = controller.createDocumentFragment(startFrag, endFrag);

                        List<AuthorNode> contentOfThisCell = ((AuthorElement) selectedCell).getContentNodes();
                        int endThisFrag = contentOfThisCell.get(contentOfThisCell.size() - 1).getEndOffset();

                        controller.insertFragment(endThisFrag + 1, fragOfBeCell);
                    }

                    controller.deleteNode(belowCell);

                    controller.setAttribute("rowspan", new AttrValue("" + (thisRowSpan + belRowSpan)), (AuthorElement) selectedCell);


                } else {
                    int[] cellIndex = authorAccess.getTableAccess().getTableCellIndex((AuthorElement) selectedCell);

                    int thisRowSpan = 0;

                    try{
                        thisRowSpan = Integer.valueOf(((AuthorElement) selectedCell).getAttribute("rowspan").getValue());
                    } catch (Exception e) {}

                    if (thisRowSpan > 1){

                        if (thisRowSpan == 2)
                            controller.removeAttribute("rowspan", (AuthorElement) selectedCell);
                        else
                            controller.setAttribute("rowspan", new AttrValue("" + --thisRowSpan), (AuthorElement) selectedCell);

                        AuthorElement belowCell = authorAccess.getTableAccess().getTableCellBelow((AuthorElement) selectedCell);

                        int[] coord = authorAccess.getTableAccess().getTableCellIndex(belowCell);

                        AuthorDocumentFragment newFrag = controller.createNewDocumentFragmentInContext("<ячейка/>", belowCell.getStartOffset());
                        controller.insertFragment(belowCell.getStartOffset(), newFrag);

                        AuthorElement insertedCell = authorAccess.getTableAccess().getTableCellAt(coord[0], coord[1], (AuthorElement) table);

                        if (coord[0] == 0 & coord[1] == 0) {
                            controller.setAttribute("border-left", new AttrValue("1px solid #000000"), insertedCell);
                            controller.setAttribute("border-right", new AttrValue("1px solid #000000"), insertedCell);
                            controller.setAttribute("border-top", new AttrValue("1px solid #000000"), insertedCell);
                            controller.setAttribute("border-bottom", new AttrValue("1px solid #000000"), insertedCell);
                        } else if (coord[0] == 0 & coord[1] > 0) {
                            controller.setAttribute("border-right", new AttrValue("1px solid #000000"), insertedCell);
                            controller.setAttribute("border-top", new AttrValue("1px solid #000000"), insertedCell);
                            controller.setAttribute("border-bottom", new AttrValue("1px solid #000000"), insertedCell);
                        } else if (coord[0] > 0 & coord[1] == 0) {
                            controller.setAttribute("border-left", new AttrValue("1px solid #000000"), insertedCell);
                            controller.setAttribute("border-right", new AttrValue("1px solid #000000"), insertedCell);
                            controller.setAttribute("border-bottom", new AttrValue("1px solid #000000"), insertedCell);
                        } else if (coord[0] > 0 & coord[1] > 0) {
                            controller.setAttribute("border-right", new AttrValue("1px solid #000000"), insertedCell);
                            controller.setAttribute("border-bottom", new AttrValue("1px solid #000000"), insertedCell);
                        }

                    }

                }

                authorAccess.getEditorAccess().setCaretPosition(initialCaretOffset);

            } catch (BadLocationException e) {
                e.printStackTrace();
            }
            controller.endCompoundEdit();
        }
    }

    public ArgumentDescriptor[] getArguments() {
        ArgumentDescriptor[] res = {
                new ArgumentDescriptor("режим", ArgumentDescriptor.TYPE_STRING, ""),
        };
        return res;
    }

    public String getDescription() {
        return null;  //To change body of implemented methods use File | Settings | File Templates.
    }
}
